package org.ruizhijie.run.tcp;

import org.ruizhijie.run.TcpServer;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TCPServerHandler extends ChannelInboundHandlerAdapter {
	public TCPServerHandler() {
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		TcpServer.getMap().put(getIPString(ctx), ctx.channel());
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object source) throws Exception {
		// 拿到传过来的msg数据，开始处理
//		ByteBuf recvmg = (ByteBuf) source;// 转化为ByteBuf
//		ctx.writeAndFlush(respmsg);// 收到及发送，这里如果没有writeAndFlush，上面声明的ByteBuf需要ReferenceCountUtil.release主动释放
		System.err.println("channel read");
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		System.err.println("userEventTriggered");
	}

	public static String getIPString(ChannelHandlerContext ctx) {
		String ipString = "";
		String socketString = ctx.channel().remoteAddress().toString();
		int colonAt = socketString.indexOf(":");
		ipString = socketString.substring(1, colonAt);
		return ipString;
	}
}
